package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.dto.NoticeCreateDTO;
import com.intelligent.dto.NoticeDTO;
import com.intelligent.dto.NoticeQueryDTO;
import com.intelligent.entity.Notice;
import com.intelligent.entity.UserNotice;
import com.intelligent.mapper.NoticeMapper;
import com.intelligent.service.NoticeService;
import com.intelligent.service.UserNoticeService;
import com.intelligent.service.NotificationPushService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【notice(通知信息表)】的数据库操作Service实现
* @createDate 2025-09-02 11:43:28
*/
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice>
    implements NoticeService{

    @Autowired
    private UserNoticeService userNoticeService;
    
    @Autowired
    private NotificationPushService notificationPushService;

    @Override
    @Transactional
    public Integer createNotice(NoticeCreateDTO createDTO) {
        Notice notice = new Notice();
        BeanUtils.copyProperties(createDTO, notice);
        notice.setCreateTime(new Date());
        notice.setUpdateTime(new Date());
        
        // 如果是立即发布
        if (Boolean.TRUE.equals(createDTO.getIsPublish())) {
            notice.setIsPublished(1);
            notice.setPublishTime(new Date());
        } else {
            notice.setIsPublished(0);
        }
        
        save(notice);
        
        // 如果是立即发布且有接收人，创建用户通知关联并推送消息
        if (Boolean.TRUE.equals(createDTO.getIsPublish()) && 
            createDTO.getReceiverIds() != null && !createDTO.getReceiverIds().isEmpty()) {
            userNoticeService.createUserNotices(notice.getNoticeId(), createDTO.getReceiverIds());
            
            // 推送消息给指定用户
            List<String> userIdStrList = createDTO.getReceiverIds().stream()
                    .map(String::valueOf)
                    .collect(Collectors.toList());
            notificationPushService.pushNoticeToUsers(userIdStrList, notice);
        }
        
        return notice.getNoticeId();
    }

    @Override
    @Transactional
    public Boolean updateNotice(NoticeCreateDTO createDTO) {
        if (createDTO.getNoticeId() == null) {
            return false;
        }
        
        Notice notice = getById(createDTO.getNoticeId());
        if (notice == null) {
            return false;
        }
        
        BeanUtils.copyProperties(createDTO, notice);
        notice.setUpdateTime(new Date());
        
        return updateById(notice);
    }

    @Override
    public IPage<NoticeDTO> pageNotices(NoticeQueryDTO queryDTO) {
        Page<Notice> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        
        // 标题模糊查询
        if (StringUtils.hasText(queryDTO.getNoticeTitle())) {
            queryWrapper.like(Notice::getNoticeTitle, queryDTO.getNoticeTitle());
        }
        
        // 状态查询
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(Notice::getStatus, queryDTO.getStatus());
        }
        
        // 类型查询
        if (queryDTO.getNoticeType() != null) {
            queryWrapper.eq(Notice::getNoticeType, queryDTO.getNoticeType());
        }
        
        // 发布人查询
        if (queryDTO.getPublishId() != null) {
            queryWrapper.eq(Notice::getPublishId, queryDTO.getPublishId());
        }
        
        // 发布状态查询
        if (queryDTO.getIsPublished() != null) {
            queryWrapper.eq(Notice::getIsPublished, queryDTO.getIsPublished());
        }
        
        // 时间范围查询
        if (queryDTO.getStartTime() != null) {
            queryWrapper.ge(Notice::getCreateTime, queryDTO.getStartTime());
        }
        if (queryDTO.getEndTime() != null) {
            queryWrapper.le(Notice::getCreateTime, queryDTO.getEndTime());
        }
        
        // 排序
        if (StringUtils.hasText(queryDTO.getOrderBy())) {
            if ("createTime".equals(queryDTO.getOrderBy())) {
                queryWrapper.orderByDesc(Notice::getCreateTime);
            } else if ("publishTime".equals(queryDTO.getOrderBy())) {
                queryWrapper.orderByDesc(Notice::getPublishTime);
            }
        } else {
            queryWrapper.orderByDesc(Notice::getCreateTime);
        }
        
        IPage<Notice> noticePage = page(page, queryWrapper);
        
        // 转换为DTO
        IPage<NoticeDTO> dtoPage = new Page<>();
        BeanUtils.copyProperties(noticePage, dtoPage);
        
        List<NoticeDTO> dtoList = noticePage.getRecords().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        dtoPage.setRecords(dtoList);
        
        return dtoPage;
    }

    @Override
    public IPage<NoticeDTO> getUserNotices(Long userId, NoticeQueryDTO queryDTO) {
        Page<Notice> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        
        // 只查询已发布的通知
        queryWrapper.eq(Notice::getIsPublished, 1);
        
        // 标题模糊查询
        if (StringUtils.hasText(queryDTO.getNoticeTitle())) {
            queryWrapper.like(Notice::getNoticeTitle, queryDTO.getNoticeTitle());
        }
        
        // 类型查询
        if (queryDTO.getNoticeType() != null) {
            queryWrapper.eq(Notice::getNoticeType, queryDTO.getNoticeType());
        }
        
        // 发布人查询
        if (queryDTO.getPublishId() != null) {
            queryWrapper.eq(Notice::getPublishId, queryDTO.getPublishId());
        }
        
        // 按发布时间倒序
        queryWrapper.orderByDesc(Notice::getPublishTime);
        
        IPage<Notice> noticePage = page(page, queryWrapper);
        
        // 转换为DTO并设置用户已读状态
        List<NoticeDTO> dtoList = noticePage.getRecords().stream().map(notice -> {
            NoticeDTO dto = convertToDTO(notice);
            
            // 查询用户对该通知的已读状态
            UserNotice userNotice = userNoticeService.getUserNoticeStatus(notice.getNoticeId(), userId);
            if (userNotice != null) {
                dto.setReadStatus(userNotice.getReadStatus());
                dto.setReadTime(userNotice.getReadTime());
            } else {
                // 如果用户通知记录不存在，自动创建一个未读记录
                UserNotice newUserNotice = new UserNotice();
                newUserNotice.setNoticeId(notice.getNoticeId());
                newUserNotice.setUserId(userId);
                newUserNotice.setReadStatus(0);
                newUserNotice.setCreateTime(new Date());
                boolean saved = userNoticeService.save(newUserNotice);
                
                if (saved) {
                    dto.setReadStatus(0);
                    dto.setReadTime(null);
                } else {
                    // 如果保存失败，设置默认值
                    dto.setReadStatus(0);
                    dto.setReadTime(null);
                }
            }
            
            return dto;
        }).collect(Collectors.toList());
        
        Page<NoticeDTO> resultPage = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        resultPage.setRecords(dtoList);
        resultPage.setTotal(noticePage.getTotal());
        resultPage.setSize(noticePage.getSize());
        resultPage.setCurrent(noticePage.getCurrent());
        resultPage.setPages(noticePage.getPages());
        
        return resultPage;
    }

    @Override
    public Boolean markAsRead(Integer noticeId, Long userId) {
        Boolean result = userNoticeService.markAsRead(noticeId, userId);
        if (result) {
            // 推送未读数量更新
            Integer unreadCount = userNoticeService.getUnreadCount(userId);
            notificationPushService.pushUnreadCountUpdate(String.valueOf(userId), unreadCount);
            
            // 推送通知状态更新
            notificationPushService.pushNoticeStatusUpdate(String.valueOf(userId), noticeId, "read");
        }
        return result;
    }

    @Override
    public Integer getUnreadCount(Long userId) {
        return userNoticeService.getUnreadCount(userId);
    }

    @Override
    @Transactional
    public Boolean publishNotice(Integer noticeId) {
        Notice notice = getById(noticeId);
        if (notice == null) {
            return false;
        }
        
        notice.setIsPublished(1);
        notice.setPublishTime(new Date());
        notice.setUpdateTime(new Date());
        
        return updateById(notice);
    }

    @Override
    public Boolean deleteNotice(Integer noticeId) {
        return removeById(noticeId);
    }

    @Override
    @Transactional
    public Boolean batchMarkAsRead(List<Integer> noticeIds, Long userId) {
        Boolean result = userNoticeService.batchMarkAsRead(noticeIds, userId);
        if (result) {
            // 推送未读数量更新
            Integer unreadCount = userNoticeService.getUnreadCount(userId);
            notificationPushService.pushUnreadCountUpdate(String.valueOf(userId), unreadCount);
        }
        return result;
    }
    
    /**
     * 转换为DTO
     */
    private NoticeDTO convertToDTO(Notice notice) {
        NoticeDTO dto = new NoticeDTO();
        BeanUtils.copyProperties(notice, dto);
        // 这里可以添加更多的转换逻辑，比如获取发布人姓名等
        return dto;
    }
}




